package com.spbdx.quartz.task;

import com.spbdx.common.constant.CacheConstants;
import com.spbdx.common.core.domain.entity.SysUser;
import com.spbdx.common.core.redis.RedisCache;
import com.spbdx.common.utils.WXUtils;
import com.spbdx.system.mapper.SysUserMapper;
import com.spbdx.system.service.ISysConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

/**
 * Description 公众号
 *
 * @author chenwei
 * @version 1.0
 * @date 2024/1/4 10:30
 */
@Component("wechatTask")
public class WechatTask {

    @Resource
    private SysUserMapper userMapper;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    private RedisCache redisCache;

    /**
     * 每天500次上限
     */
    public synchronized void getWechatUsers() {
        String appid = sysConfigService.selectConfigByKey("wechat.appid");
        String secret = sysConfigService.selectConfigByKey("wechat.secret");
        List<Map<String, String>> list = WXUtils.getWechatOpenid(appid, secret, "");
        list.forEach(map -> {
            //公众号openid
            String openid = map.get("openid");
            String unionid = map.get("unionid");

            SysUser sysUser = new SysUser();
            sysUser.setUnionid(unionid);
            List<SysUser> sysUsers = userMapper.selectUserList(sysUser);
            if (CollectionUtils.isNotEmpty(sysUsers)) {
                sysUser.setUserId(sysUsers.get(0).getUserId());
                sysUser.setOpenid2(openid);
                userMapper.updateUser(sysUser);
            }
        });
        if (CollectionUtils.isNotEmpty(list)) {
            redisCache.setCacheSet(CacheConstants.WX_FOCUS_USERS, new HashSet<>(list));
        }
    }
}
